package com.bodystm.algorithm;
/**
 * 呼吸算法
 * @author rxz
 *
 */
public class BreathRate {
	/*
	 * Desc: Calc Breath Rate
	 * Params:
	 *      input:head address of respiratory data
	 *      length:data length
	 * Return:
	 *      Breath Rate;
	 * Author:
	 *      WangYaLiang 2017/12/29
	 */
	public static float Breath(float[] input, int length)     //输入信号及信号长度；信号长度定为1250点；
	{
	    /*FILE *fp;

	    fopen_s(&fp, "sig.txt", "w");*/

	    int[] loc = new int[3];



	    int i,j;

	    int k = 0;

	    int temp;

	    float breath_T = 0;;

	    float sig_L[] = new float[1250]; // 数据长度；待定；
	    float sig_R[] = new float[1250];
	    float sig[] = new float[1250];
	    int loc_LR[] = new int[1000];

	    for (i = 1; i < length - 1; i++)
	    {
	        if (input[i] > input[i - 1] && input[i] >= input[i + 1])
	        {
	            sig_L[i] = input[i];
	        }
	    }

	    for (i = 1; i < length - 1; i++)
	    {
	        if (input[i] >= input[i - 1] && input[i] > input[i + 1])
	        {
	            sig_R[i] = input[i];
	        }
	    }

	    for (i = 0; i < length; i++)
	    {
	        if (sig_L[i] > 0)
	        {
	            sig[i] = sig_L[i];
	        }
	        if (sig_R[i] > 0)
	        {
	            sig[i] = sig_R[i];
	        }
	    }

	    k = 0;
	    for (i = 0; i < length; i++)
	    {
	        if (sig[i] > 0)
	        {
	            loc_LR[k] = i;
	            k = k + 1;
	        }
	    }

	    j = 0;
	    for (i = 0; i < k-2; i++)
	    {
	        if ((sig[loc_LR[i]] == sig_L[loc_LR[i]] && sig[loc_LR[i + 1]] == sig_R[loc_LR[i + 1]]) || (sig[loc_LR[i]] == sig_R[loc_LR[i]] && sig[loc_LR[i + 1]] == sig_L[loc_LR[i + 1]]))
	        {
	            loc[j] = (loc_LR[i] + loc_LR[i + 1]) / 2;
	            j = j + 1;
	        }
	        if (j > 2)
	        {
	            break;
	        }
	    }
	    //for (i = 0; i < 2500; i++)
	    //{

	    //	fprintf(fp, "%f ", sig[i]);

	    //}

	    //fclose(fp);



	    if (loc[2] > 0)
	    {
	        temp = 0;
	        temp = (loc[2] - loc[0]) / 2;
	        breath_T = (float)30 * 125 / temp;
	    }
	    else if (loc[1] > 0)
	    {
	        temp = 0;
	        temp = loc[1] - loc[0];
	        breath_T = (float)30 * 125 / temp;
	    }

	    if (Math.abs(input[loc[1]] - input[loc[0]]) < 10)  //500为阈值，低于阈值的波动可看作直线；呼吸率为0；
	    {
	        breath_T = 0;
	    }
	    //printf("loc=%d\n", loc[0]);
	    //printf("loc=%d\n", loc[1]);
	    //printf("loc=%d\n", loc[2]);

	    return breath_T;                                  //返回呼吸率；
	}
}
